/**
 * 
 */
package trungsi.gea.photos.client

import java.awt.image.BufferedImageimport java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.imageio.ImageIO
import com.mortennobel.imagescaling.ResampleOpimport com.mortennobel.imagescaling.AdvancedResizeOpimport com.mortennobel.imagescaling.AdvancedResizeOp.UnsharpenMask
/**
 * @author trungsi
 *
 */
public class ImageUtils {
	static {
		BufferedImage.metaClass.downSize = {width, height, format ->
			int newWidth = width < delegate.width ? width : delegate.width
			int newHeight = newWidth/delegate.width * delegate.height
			if (newHeight > height) {
				newHeight = height
				newWidth = newHeight/delegate.height * delegate.width
			}
			
			/*BufferedImage newImage = new BufferedImage(newWidth, newHeight, delegate.getType())
	        Graphics2D g = newImage.getGraphics()
	        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
	        g.drawImage(delegate, 0, 0, newWidth, newHeight, 0, 0, delegate.width, delegate.height, null)
	        g.dispose()*/
	        
	        ResampleOp resampleOp = new ResampleOp(newWidth, newHeight)
			resampleOp.setUnsharpenMask(UnsharpenMask.Normal)
	        BufferedImage newImage = resampleOp.filter(delegate, null)
	        OutputStream output = new ByteArrayOutputStream()
	        ImageIO.write(newImage, format, output)
	        
	        return new ByteArrayInputStream(output.toByteArray())
		}
	}
	
	static InputStream downSize(file, width, height) {
		loadImg(file).downSize(width, height, getFormat(file))
	}
	
	static BufferedImage loadImg(file) {
		ImageIO.read(file)
	}
	
	static String getFormat(file) {
        file.name[file.name.lastIndexOf('.')+1..-1]?.toLowerCase()
    }
}
